package com.hzit.auth.service.impl;

import cn.hutool.json.JSONUtil;
import com.hzit.auth.mapper.UserMapper;
import com.hzit.auth.service.ITokenService;
import com.hzit.constant.HzitConstants;
import com.hzit.entity.LoginUser;
import com.hzit.entity.User;
import com.hzit.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@Service
public class TokenServiceImpl implements ITokenService {
	@Autowired
	private StringRedisTemplate redisTemplate;
	@Autowired
	private UserMapper userMapper;

	//1. 保存token
	@Override
	public Map<String, Object> createToken(User user) {
		//1.1 生成token
		String token = UUID.randomUUID().toString().replace("-","");

		//1.2 保存到redis中
		String key = getKey(token);
		//1.3 定义登录用户对象
		LoginUser loginUser = new LoginUser();
		loginUser.setToken(token);
		loginUser.setUser(user);
		List<String> permissions =  userMapper.findPermissionsByUsername(user.getUsername());
		loginUser.setPermissions(permissions);
		//1.4 保存数据到redis中
		redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(loginUser));

		//1.5 返回数据给前端
		Map<String,Object> map = new HashMap<>();
		map.put(HzitConstants.USER_KEY,token);
		//1.5.1 使用jwt加密数据
		String jwtToken = JwtUtil.createToken(HzitConstants.JWT_TOKEN_KEY, map);
		//1.5.2 定义返回map
		Map<String,Object> result = new HashMap<>();
		result.put("access_token",jwtToken);
		return result;
	}

	private String getKey(String token) {
		return HzitConstants.REDIS_KEY_PREFIX + token;
	}
}
